<script setup>
import {computed, onMounted, ref, watch} from "vue";

import {Dialog, DialogPanel, DialogTitle, TransitionChild, TransitionRoot} from "@headlessui/vue";
import {XMarkIcon} from "@heroicons/vue/24/outline/index.js";
import {getCartAPI, removeCartAPI} from "../apis/cart.js";
import {message} from "ant-design-vue";
import {orderAPI} from "../apis/order.js";
import {getJwt} from "../utils/localStorage.js";
import Eeweima from "./Eeweima.vue";

// 购物车商品
const chartProducts = ref([])

const chartOpen = ref(false)

defineExpose({
  // 修改展开状态
  toggleOpen(value) {
    chartOpen.value = value
  }
})

// 获取购物车数据
const getChartData = () => {
  getCartAPI().then((res) => {
    console.log('获取购物车数据', res)
    if (res.code === '0000') {
      chartProducts.value = res.data
      message.success(res.info)
    } else {
      message.error(res.info)
    }
  })
}

watch(chartOpen, (newValue, oldValue) => {
  if (newValue === true) {
    getChartData()
  }
})


// 计算总价
const total = computed(() => {
  let all = 0
  chartProducts.value.forEach((item) => {
    all += (item.amount * item.totalCount)
  })
  return all.toFixed(2)
})


// 下单
const order = (product) => {
  let data = {
    userId: product.userId,
    sku: product.sku,
    totalAmount: product.totalCount * product.amount,
  }
  orderAPI(data).then((res) => {
    console.log('用户下单', res)
    if (res.code === '0000'){
      message.success(res.info)
      erweimaurl.value = res.data
      erweima.value.openModal()
      getChartData()
    }else {
      message.error(res.info)
    }
  })
}

// 二维码地址
const erweimaurl = ref('')

// 二维码对象
const erweima = ref(null)


// 移除购物车商品
const removeChartProduct = (cartId) => {

  removeCartAPI(cartId).then((res) => {
    console.log('移除购物车商品', res)
    if (res.code === '0000') {
      message.success(res.info)
      getChartData()
    } else {
      message.error(res.info)
    }
  })
}
</script>

<template>

<!--  二维码-->
  <Eeweima :erweimaurl="erweimaurl" ref="erweima"/>
  <!--  购物车-->
  <TransitionRoot as="template" :show="chartOpen">
    <Dialog class="relative z-50" @close="chartOpen = false">
      <TransitionChild as="template" enter="ease-in-out duration-500" enter-from="opacity-0" enter-to="opacity-100"
                       leave="ease-in-out duration-500" leave-from="opacity-100" leave-to="opacity-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"/>
      </TransitionChild>

      <div class="fixed inset-0 overflow-hidden">
        <div class="absolute inset-0 overflow-hidden">
          <div class="pointer-events-none fixed inset-y-0 right-0 flex max-w-full pl-10">
            <TransitionChild as="template" enter="transform transition ease-in-out duration-500 sm:duration-700"
                             enter-from="translate-x-full" enter-to="translate-x-0"
                             leave="transform transition ease-in-out duration-500 sm:duration-700"
                             leave-from="translate-x-0" leave-to="translate-x-full">
              <DialogPanel class="pointer-events-auto w-screen max-w-md">
                <div class="flex h-full flex-col overflow-y-scroll bg-white shadow-xl">
                  <div class="flex-1 overflow-y-auto px-4 py-6 sm:px-6">
                    <div class="flex items-start justify-between">
                      <DialogTitle class="text-lg font-medium text-gray-900">购物车</DialogTitle>
                      <div class="ml-3 flex h-7 items-center">
                        <button type="button" class="relative -m-2 p-2 text-gray-400 hover:text-gray-500"
                                @click="chartOpen = false">
                          <span class="absolute -inset-0.5"/>
                          <span class="sr-only">Close panel</span>
                          <XMarkIcon class="h-6 w-6" aria-hidden="true"/>
                        </button>
                      </div>
                    </div>

                    <div class="mt-8">
                      <div class="flow-root">
                        <ul role="list" class="-my-6 divide-y divide-gray-200">
                          <li v-for="product in chartProducts" :key="product.sku" class="flex py-6">
                            <div class="h-24 w-24 flex-shrink-0 overflow-hidden rounded-md border border-gray-200">
                              <img
                                  src="https://store.storeimages.cdn-apple.com/1/as-images.apple.com/is/iphone-15-model-unselect-gallery-1-202309?wid=5120&hei=2880&fmt=webp&qlt=70&.v=aVFiZEF4WDEvUWJNSU5HRDg4cklnTGdzSmpObkZCM3MrNmJ5SkhESlNDZ1UwRE05YU1MZ0lYWk55ZU5FOENXWkpFd0xhWDVibStLdGRYRmxkNGI4VTdpMGJRT0ppMjh4RlRZQkc0Q3FZZEI4UW55RWdXT3BFc2NrR2VEb1pCOGo=&traceId=1"
                                  :alt="product.productCover"
                                  class="h-full w-full object-cover object-center"/>
                            </div>

                            <div class="ml-4 flex flex-1 flex-col">
                              <div>
                                <div class="flex justify-between text-base font-medium text-gray-900">
                                  <h3>
                                    <a href="#">{{ product.productTitle }}</a>
                                  </h3>
                                  <p class="ml-4">{{ product.amount * product.totalCount }}</p>
                                </div>
                                <!--                                <p class="mt-1 text-sm text-gray-500">{{ product.color }}</p>-->
                              </div>
                              <div class="flex flex-1 items-end justify-between text-sm">
                                <p class="text-gray-500">数量 {{ product.totalCount }}</p>

                                <div class="flex gap-2.5">
                                  <button
                                      @click="order(product)"
                                      type="button"
                                      class="font-medium text-indigo-600 hover:text-indigo-500">
                                    下单
                                  </button>
                                  <button
                                      @click="removeChartProduct(product.cartId)"
                                      type="button" class="font-medium text-indigo-600 hover:text-indigo-500">
                                    移除
                                  </button>
                                </div>
                              </div>
                            </div>
                          </li>
                        </ul>
                      </div>
                    </div>
                  </div>

                  <div class="border-t border-gray-200 px-4 py-6 sm:px-6">

                    <p class="mt-0.5 text-sm text-gray-500">结账时计算运费和税费。</p>

                    <div class="mt-6 flex justify-center text-center text-sm text-gray-500">
                      <p>
                        or{{ ' ' }}
                        <button type="button" class="font-medium text-indigo-600 hover:text-indigo-500"
                                @click="chartOpen = false">
                          继续购物
                          <span aria-hidden="true"> &rarr;</span>
                        </button>
                      </p>
                    </div>
                  </div>
                </div>
              </DialogPanel>
            </TransitionChild>
          </div>
        </div>
      </div>
    </Dialog>
  </TransitionRoot>
</template>

<style scoped>

</style>